package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.MenuActivity;
import com.example.hcd.R;
import com.example.hcd.adapt.FileAdapter;
import com.example.hcd.datamanage.LoadedImage;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.PurchaseData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.FileUtils;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.CommonDialog;
import com.example.hcd.tool.DigitalTool;
import com.example.hcd.tool.MyGridView;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PurchaseApply extends BaseActivity implements OnClickListener
{

	private PurchaseApply context;

	private View main_view;

	private LayoutInflater inflater;

	private EditText amoutEdit;

	private EditText bigAmout;

	private PurchaseData purchaseData;



	private TextView xiaedit1;
	private TextView xiaedit2;

	// 是否有发票下拉popwindows
	private CommonDialog popipwindow,popipwindow1,popipwindow2,popipwindow3;
	// pop界面
	private View popview2;
	private TextView xiaedit3,xiaedit4;

	private LinearLayout bankbg;

	// 附件的GridView
	private MyGridView gridview;

	// 附件的地址集合
	private ArrayList<String> listfile = new ArrayList<String>();
	private ArrayList<String> listfileCatch = new ArrayList<String>();

	private FileAdapter fileAdapter;

	// 获取下一步处理人
	private ArrayList<PeopleNextData> peoples_next;
	private TextView nextPeople;

	private RelativeLayout nextPeopleBg;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "PurchaseApply";
		inflater = LayoutInflater.from(this);
		context = this;
		main_view = inflater.inflate(R.layout.purchase_apply_view, null);
		setContentView(main_view);

		{
			RelativeLayout view = (RelativeLayout) main_view.findViewById(R.id.is_have_receipt);
			view.setVisibility(View.VISIBLE);

			xiaedit3 = (TextView) main_view.findViewById(R.id.title52);
			xiaedit3.setOnClickListener(this);
			xiaedit4 =(TextView) main_view.findViewById(R.id.title62);
//			xiaedit4.setOnClickListener(this);
			RelativeLayout xialaimage = (RelativeLayout) main_view.findViewById(R.id.btn_image3);
			xialaimage.setOnClickListener(this);
			RelativeLayout xialaimage1 = (RelativeLayout) main_view.findViewById(R.id.btn_image5);
			xialaimage1.setOnClickListener(this);

			String[] texts = new String[] { " - - ", "无票", "有票" };
			popipwindow2 = new CommonDialog(this);
			for (int i = 0; i < texts.length; i++)
			{
				final View item = (View) inflater.inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(texts[i]);
				popipwindow2.addView(item);
				xiaedit3.setText(texts[0]);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit3.setText(text.getText().toString());
						popipwindow2.dismiss();
					}
				});

			}

			String[] texts1 = new String[] {  "否", "是" };
			popipwindow3 = new CommonDialog(this);
			for (int i = 0; i < texts1.length; i++)
			{
				final View item = (View) inflater.inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(texts1[i]);
				popipwindow3.addView(item);
				xiaedit4.setText(texts1[0]);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit4.setText(text.getText().toString());
						popipwindow3.dismiss();
					}
				});

			}


		}

		initview();
	}

	private void initview()
	{
		// 借款申請人
		EditText applyEdit = (EditText) findViewById(R.id.editText8);
		applyEdit.setText(UserInfo.getUserInfor().getName() + "(" + UserInfo.getUserInfor().getDepartmnet() + ")");

		purchaseData = new PurchaseData(null);
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		uploadBtn.setOnClickListener(context);

		bankbg = (LinearLayout) main_view.findViewById(R.id.bankbg);

		// 金额
		amoutEdit = (EditText) findViewById(R.id.editText6);
		bigAmout = (EditText) findViewById(R.id.editText7);
		amoutEdit.addTextChangedListener(new TextWatcher() {

			private boolean isChanged;

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
			{
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s)
			{
				// TODO Auto-generated method stub
				if (amoutEdit.getText().toString().equals("."))
				{
					return;
				}
				if (isChanged)
				{// ----->如果字符未改变则返回
					return;
				}
				String str = s.toString();

				isChanged = true;
				String cuttedStr = str;
				boolean flag = false;
				/* 删除字符串中的dot */
				for (int i = str.length() - 1; i >= 0; i--)
				{
					char c = str.charAt(i);
					if ('.' == c && i == str.length() - 4)
					{
						cuttedStr = str.substring(0, i + 3);
						if (cuttedStr.endsWith("."))
						{
							cuttedStr = cuttedStr.substring(0, i + 1);
						}
						flag = true;
						break;
					}
				}

				if (flag)
				{
					amoutEdit.setText(cuttedStr);
					// 设置新光标所在的位置
					Selection.setSelection((Editable) amoutEdit.getText(), cuttedStr.length());
				}

				str = amoutEdit.getText().toString();
				if (str.contains("."))
				{
					int numlength = 0;
					for (int i = 0; i < str.length() - 1; i++)
					{
						char c = str.charAt(i);
						if (c == '.')
						{
							break;
						} else
						{
							numlength++;
						}

					}
					if (numlength > 8)
					{
						int index = amoutEdit.getSelectionStart();
						Editable editable = amoutEdit.getText();
						editable.delete(index - 1, index);
					}

				} else
				{
					if (str.length() > 8)
					{
						int index = amoutEdit.getSelectionStart();
						Editable editable = amoutEdit.getText();
						editable.delete(index - 1, index);
					}
				}

				if (amoutEdit.getText().toString() == null || amoutEdit.getText().toString().equals(""))
				{
					str = "0";
				} else
				{
					str = amoutEdit.getText().toString();

				}
				Double numOfmoney = Double.parseDouble(str);

				bigAmout.setText(DigitalTool.toBigMode(numOfmoney));

				isChanged = false;

			}
		});
		xiaedit1 = (TextView) main_view.findViewById(R.id.title11);
		xiaedit1.setOnClickListener(this);
		xiaedit2 = (TextView) main_view.findViewById(R.id.title21);
		xiaedit2.setOnClickListener(this);

		findViewById(R.id.btn_image1).setOnClickListener(context);

		findViewById(R.id.btn_image2).setOnClickListener(context);
		
	

		if (InternetKeep.getInstence().isSystemInfoLoad)
		{

			popipwindow = new CommonDialog(this);

			for (int i = 0; i < InternetKeep.getInstence().getProjectInfolist().size(); i++)
			{
				final View item = (View) LayoutInflater.from(context).inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(InternetKeep.getInstence().getProjectInfolist().get(i).pur_Pay_Proj_Info);
				popipwindow.addView(item);
				xiaedit1.setText(InternetKeep.getInstence().getProjectInfolist().get(0).pur_Pay_Proj_Info);
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit1.setText(text.getText().toString());
						popipwindow.dismiss();
					}
				});
			}

			popipwindow1 = new CommonDialog(this);

			for (int i = 0; i < InternetKeep.getInstence().getPurchaseTypelist().size(); i++)
			{
				final View item = (View) LayoutInflater.from(context).inflate(R.layout.common_dialog_item, null);

				final TextView text = (TextView) item.findViewById(R.id.item_text);
				text.setText(InternetKeep.getInstence().getPurchaseTypelist().get(i).pur_Pay_Proj_Info);
				popipwindow1.addView(item);
				xiaedit2.setText(InternetKeep.getInstence().getPurchaseTypelist().get(2).pur_Pay_Proj_Info);
				IsbankbgShowOrHide();
				text.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0)
					{
						xiaedit2.setText(text.getText().toString());
						IsbankbgShowOrHide();
						popipwindow1.dismiss();
					}
				});
			}

		} else
		{
			// Toast.makeText(context, "报销项目加载失败", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "付款方式加载失败");
			finish();
		}

		gridview = (MyGridView) main_view.findViewById(R.id.file_gridview);
		gridview.setVisibility(View.GONE);
		fileAdapter = new FileAdapter(this);
		gridview.setAdapter(fileAdapter);
		// gridview.setHaveScrollbar(false);
		gridview.setOnItemLongClickListener(new OnItemLongClickListener() {
			// GridList长按了某项
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// 这里的arg2代表长按的位置
				fileAdapter.photos.remove(arg2);// 移除数据
				listfile.remove(arg2);

				if (fileAdapter.photos.size() == 0)
				{
					gridview.setVisibility(View.GONE);
				}

				fileAdapter.notifyDataSetInvalidated();
				return true;
			}
		});

		gridview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				// TODO Auto-generated method stub
				LoadedImage uri = fileAdapter.getItem(arg2);
				// System.out.println(uri.getText());

				if (FileUtils.isPic(getLast(uri.getPicPath())))
				{
					ArrayList<String> picpathlist = new ArrayList<String>();
					Intent intent = new Intent(PurchaseApply.this, ShowPictureList.class);
					for (int i = 0; i < listfile.size(); i++)
					{
						if (FileUtils.isPic(listfile.get(i)))
						{
							picpathlist.add(listfile.get(i));
						}
					}

					for (int i = 0; i < picpathlist.size(); i++)
					{
						if (picpathlist.get(i).equals(uri.getPicPath()))
						{
							intent.putExtra("MOREN_INDEX", i);
						}
					}

					intent.putStringArrayListExtra("PICK_PATH_LIST", picpathlist);

					intent.putExtra("IS_BENDI", true);
					startActivity(intent);
				} else
				{
					Intent intent = new Intent(PurchaseApply.this, FileDetailActivity.class);
					intent.putExtra("FILE_URI", uri.getPicPath());
					intent.putExtra("FILE_NAME", getLast(uri.getPicPath()));
					intent.putExtra("IS_BENDI", true);
					startActivity(intent);
				}

				overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
			}
		});

		ImageView appendix_btn = (ImageView) main_view.findViewById(R.id.appendix_btn);
		appendix_btn.setOnClickListener(this);
		// 获取下一步处理人
		nextPeopleBg = (RelativeLayout) main_view.findViewById(R.id.next_people_bg);
		nextPeople = (TextView) main_view.findViewById(R.id.next_people);
		peoples_next = new ArrayList<PeopleNextData>();
		// 获取下一步处理人
		getNextPeople next = new getNextPeople();
		next.execute();

	}

	// 获取下一步处理人
	private class getNextPeople extends AsyncTask<String, Integer, String>
	{

		// private ProgressDialog mProgress;
		public getNextPeople() {
		}

		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("taskId", ""));
				response = LinkHelp.post(URLS.getNextWorkUser("purchase"), vs, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{

			if (result == null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}

			JSONObject jsonObject;
			try
			{
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code"))
				{
					String status = jsonObject.getString("status");
					if (status.equals("success"))
					{
						{
							if (result.contains("workUserInfo"))
							{
								JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
								for (int i = 0; i < peoples.length(); i++)
								{
									PeopleNextData data = new PeopleNextData();
									JSONObject myJS = peoples.getJSONObject(i);
									data.setUserId(myJS.getString("userId"));
									data.setUserName(myJS.getString("userName"));
									data.setDepartmentId(myJS.getString("departmentId"));
									data.setDepartmentName(myJS.getString("departmentName"));
									data.setCompanyId(myJS.getString("companyId"));
									data.setCompanyName(myJS.getString("companyName"));
									data.setIsHead(myJS.getString("isHead"));
									data.setCode(myJS.getString("code"));
									peoples_next.add(data);
								}
								if (peoples_next.size() >= 1)
								{
									nextPeople.setText(peoples_next.get(0).getUserName() + "("
											+ peoples_next.get(0).getDepartmentName() + ")");
								} else
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("noNeedWorkUserId"))
							{
								if (jsonObject.getString("noNeedWorkUserId").equals("true"))
								{
									nextPeople.setText("下一步不需要处理人");
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("msg"))
							{
								nextPeople.setText(jsonObject.getString("msg"));

								if (jsonObject.getString("msg").contains("不需要"))
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else
							{
								System.out.println("Shit!服务器给的什么破数据");
							}

						}

					} else
					{
						String msg = jsonObject.getString("msg");
						// Toast.makeText(context, msg,
						// Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
						nextPeople.setText("空");
						nextPeopleBg.setVisibility(View.GONE);
					}

				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}



	private String getLast(String path)
	{
		String a[] = path.split("/");
		return a[a.length - 1];
	}

	public boolean IsbankbgShowOrHide()
	{
		if (xiaedit2.getText().equals("现金"))
		{
			bankbg.setVisibility(View.GONE);
			return false;
		} else
		{
			bankbg.setVisibility(View.VISIBLE);
			return true;
		}
	}

	@Override
	public void onClick(View arg0)
	{
		// TODO Auto-generated method stub
		int id = arg0.getId();
		// //隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(main_view.getWindowToken(), 0);

		getCurrentFocus().clearFocus();
		EditText edit = (EditText) main_view.findViewById(R.id.edit_focuse_unable);
		edit.setFocusable(true);
		edit.requestFocus();

		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;

		case R.id.title_bar_btn_right:
			upload();
			break;
		case R.id.btn_image1:
		case R.id.title11:
		{
			Window window = popipwindow.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			popipwindow.show();
		}
			break;
		case R.id.btn_image2:
		case R.id.title21:
		{
			Window window = popipwindow1.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			popipwindow1.show();
		}
			break;

		case R.id.appendix_btn:
			Intent intent = new Intent(PurchaseApply.this, SelectPicActivity.class);
			intent.putExtra("type", "choosemore");
			intent.putExtra("IS_CHOOSE_FILE", true);
			startActivityForResult(intent, MenuActivity.SELECT_PHOTO);
			overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
			break;

		case R.id.title52:

		case R.id.btn_image3:
		{
			Window window = popipwindow2.getWindow();
			window.setGravity(Gravity.BOTTOM);
			window.setWindowAnimations(R.style.pop_float_win_anim_style);
			popipwindow2.show();
		}
			break;
			case R.id.btn_image5:
			{
				Window window = popipwindow3.getWindow();
				window.setGravity(Gravity.BOTTOM);
				window.setWindowAnimations(R.style.pop_float_win_anim_style);
				popipwindow3.show();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK)
		{
			switch (requestCode) {

			case MenuActivity.SELECT_PHOTO:
				// ArrayList<String> files =new ArrayList<String>();
				listfileCatch.clear();
				listfileCatch = data.getStringArrayListExtra("files");
				listfile.addAll(listfileCatch);
				initGridView();
				break;

			default:
				break;
			}
		}

	}

	private void initGridView()
	{
		new AsyncLoadedImage().execute();

	}

	/*
	 * 异步加载缩略图到LoadedImage然后调用addImage方法更新Adapter
	 */
	class AsyncLoadedImage extends AsyncTask<Object, LoadedImage, Object>
	{
		@Override
		protected Object doInBackground(Object... params)
		{

			Bitmap bitmap = null;
			Bitmap newBitmap;
			for (int i = 0; i < listfileCatch.size(); i++)
			{
				String path = listfileCatch.get(i);

				File file = new File(path);
				if (file.exists())
				{
					System.out.println(path + "存在");
					if (FileUtils.isPic(path))
					{

						try
						{
							BitmapFactory.Options options = new BitmapFactory.Options();
							options.inSampleSize = 10;
							bitmap = BitmapFactory.decodeFile(path, options);
							newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
							bitmap.recycle();
							if (newBitmap != null)
							{
								publishProgress(new LoadedImage(newBitmap, path));
							}
						} catch (Exception e)
						{
							e.printStackTrace();
						}

					} else
					{
						try
						{

							if (path.contains(".pdf"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pdf);
							} else if (path.contains(".txt"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text);
							} else if (path.contains(".doc"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.word);
							} else if (path.contains(".zip"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.zip);
							} else if (path.contains(".xls"))
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.excel);
							} else
							{
								bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.file);
							}
							newBitmap = ThumbnailUtils.extractThumbnail(bitmap, 120, 120);
							bitmap.recycle();
							if (newBitmap != null)
							{
								publishProgress(new LoadedImage(newBitmap, path));
							}
						} catch (Exception e)
						{
							e.printStackTrace();
						}

					}
				} else
				{
					listfile.remove(path);
				}

			}

			return null;
		}

		// 实时更新UI
		// onProgressUpdate()方法的参数对应于doInBackground中publishProgress方法的参数，同时也对应于
		// doInBackground的第二个参数
		@Override
		public void onProgressUpdate(LoadedImage... value)
		{
			addImage(value);
		}

		// 更新UI结束后的处理
		@Override
		protected void onPostExecute(Object result)
		{
			setProgressBarIndeterminateVisibility(false);
		}
	}

	/*
	 * 刷新Adapter
	 */
	private void addImage(LoadedImage... value)
	{
		for (LoadedImage image : value)
		{
			fileAdapter.addPhoto(image);
			fileAdapter.notifyDataSetChanged();
			gridview.setVisibility(View.VISIBLE);
		}
	}

	private void upload()
	{
		if (isCanUpload())
		{
			UpdateLoadInfo upload = new UpdateLoadInfo(purchaseData);
			upload.execute();
		}
	}

	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String>
	{
		PurchaseData purchaseData;

		private MyLoadingDialog dialog;

		public UpdateLoadInfo(PurchaseData purchaseData) {

			this.purchaseData = purchaseData;
		}

		@Override
		protected void onPreExecute()
		{
			dialog = new MyLoadingDialog(context, null, "提交中...", false);
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params)
		{
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try
			{

				MultipartEntity multipartEntity = new MultipartEntity();
				for (String fileuri : listfile)
				{
					File file = new File(fileuri);
					FileBody filebody = new FileBody(file, file.getName(), "application/octet-stream", "UTF-8");
					multipartEntity.addPart(file.getName(), filebody);
				}

				multipartEntity.addPart("title", new StringBody(purchaseData.getTitle(), Charset.forName("UTF-8")));
				multipartEntity.addPart("amount",
						new StringBody("" + purchaseData.getAmount(), Charset.forName("UTF-8")));
				multipartEntity.addPart("purchaseType",
						new StringBody(InternetKeep.getInstence().getIdBypayType(purchaseData.getPurchaseTypeName()),
								Charset.forName("UTF-8")));

				multipartEntity.addPart("useSeal",
						new StringBody(purchaseData.getUseSeal(), Charset.forName("UTF-8")));

				multipartEntity.addPart("projectName",
						new StringBody(purchaseData.getProjectName(), Charset.forName("UTF-8")));

				if (IsbankbgShowOrHide())
				{
//					multipartEntity.addPart("bankName",
//							new StringBody(purchaseData.getBankName(), Charset.forName("UTF-8")));
//					multipartEntity.addPart("bankCardId",
//							new StringBody(purchaseData.getBankCardId(), Charset.forName("UTF-8")));
					multipartEntity.addPart("supplierName",
							new StringBody(purchaseData.getSupplierName(), Charset.forName("UTF-8")));
				}

				if (xiaedit3.getText().toString().equals("") || xiaedit3.getText().toString() == null)
				{

				} else
				{
					multipartEntity.addPart("hasReceipt", new StringBody(purchaseData.getIshasReceipt(), Charset.forName("UTF-8")));
				}

				EditText edit = (EditText) main_view.findViewById(R.id.editText9);
				multipartEntity.addPart("reason", new StringBody(
						edit.getText().toString() == null ? "" : edit.getText().toString(), Charset.forName("UTF-8")));

				response = LinkHelp.UpPhotos(URLS.getPurchaseStart(), multipartEntity, false);

				if (response != null)
				{
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200)
					{
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine())
						{
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result)
		{
			JSONObject jsonObject;
			dialog.dimiss();
			try
			{
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code"))
				{
					String status = jsonObject.getString("status");
					UserInfo info = UserInfo.getUserInfor();
					if (status.equals("success"))
					{
						Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

						finish();
					} else
					{
						String msg = jsonObject.getString("msg");
						// Toast.makeText(context, msg,
						// Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
					}

				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

	}

	public boolean isCanUpload()
	{
		EditText title = (EditText) findViewById(R.id.editText);
		String titleStr = title.getText().toString();
		if (titleStr == null || titleStr.equals(""))
		{
			// Toast.makeText(context, "标题不能为空", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "标题不能为空");
			return false;
		} else
		{
			purchaseData.setTitle(titleStr);
		}

		if (xiaedit1.getText().toString().equals("请选择项目"))
		{
			// Toast.makeText(context, "请选择项目", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "请选择项目");
			return false;
		} else
		{
			purchaseData.setProjectName((xiaedit1.getText().toString()));
		}
		if (xiaedit2.getText().toString().equals("请选择付款方式"))
		{
			// Toast.makeText(context, "请选择付款方式", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "请选择付款方式");
			return false;
		} else
		{
			purchaseData.setPurchaseTypeName((xiaedit2.getText().toString()));
		}

		if (IsbankbgShowOrHide())
		{
			title = (EditText) findViewById(R.id.editText3);
			titleStr = title.getText().toString();

			if (titleStr.equals("") || titleStr == null)
			{
				// Toast.makeText(context, "供应商不能为空",
				// Toast.LENGTH_SHORT).show();
				ToastHelp.doToastInTop(context, "供应商不能为空");
				return false;
			} else
			{
				purchaseData.setSupplierName(titleStr);
			}
			title = (EditText) findViewById(R.id.editText4);
			titleStr = title.getText().toString();

			if (titleStr.equals("") || titleStr == null)
			{
				// Toast.makeText(context, "(供应商)开户银行不能为空",
				// Toast.LENGTH_SHORT).show();
//				ToastHelp.doToastInTop(context, "(供应商)开户银行不能为空");
//				return false;
			} else
			{
				purchaseData.setBankName(titleStr);
			}

			title = (EditText) findViewById(R.id.editText5);
			titleStr = title.getText().toString();

			if (titleStr.equals("") || titleStr == null)
			{
				// Toast.makeText(context, "(供应商)银行账号不能为空",
				// Toast.LENGTH_SHORT).show();
//				ToastHelp.doToastInTop(context, "(供应商)银行账号不能为空");
//				return false;
			} else
			{
				purchaseData.setBankCardId(titleStr);
			}
		}

		title = (EditText) findViewById(R.id.editText6);
		titleStr = title.getText().toString();
		if (titleStr.equals(".") || Double.parseDouble(titleStr) <= 0.00000000001)
		{
			// Toast.makeText(context, "金额输入错误", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "金额输入错误");
			return false;
		} else
		{
			purchaseData.setAmount(titleStr);
		}

		if (UserInfo.getUserInfor().isShenZhen())
		{
			if (xiaedit3.getText().toString().equals("") || xiaedit3.getText().toString() == null)
			{
				// Toast.makeText(context, "请选择报销项目",
				// Toast.LENGTH_SHORT).show();
				ToastHelp.doToast(context, "请选择是否有发票");
				return false;
			} else
			{
				// reimburseData.setProjectName(xialaEdit.getText().toString());
			}
		}
		purchaseData.setIshasReceipt(xiaedit3.getText().toString().equals(context.getResources().getText(R.string.have_receipt))?"yes":"no");
		purchaseData.setUseSeal(xiaedit4.getText().toString().equals("是")?"yes":"no");

		return true;
	}

}
